'use strict';
var gulp       = require('gulp'),
    less       = require('gulp-less'),//编译less
    mincss     = require('gulp-minify-css'),//压缩css
    cssver     = require('gulp-make-css-url-version'),//给css内部引用文件添加版本号（图片和字体）
    uglify     = require('gulp-uglify'),//压缩js
    imgmin     = require('gulp-imagemin'),//压缩图片
    // pngmin     = require('imagemin-pngquant'),
    cache      = require('gulp-cache'),//缓存，防止图片被多次压缩
    autoprefix = require('gulp-autoprefixer'),//给css3自动添加浏览器前缀
    plumber    = require('gulp-plumber'),//防止编译less出错时而停止监听文件任务
    rev        = require('gulp-rev-append'),//给静态引用文件添加版本号
    combo      = require('gulp-combo');//合并js请求


    /*编译less文件*/
    gulp.task('less',function(){
        gulp.src('less/**/*.less')
            .pipe(plumber())
            .pipe(less())
            .pipe(autoprefix('last 2 versions'))
            .pipe(gulp.dest('css/'));
    });

    /*监听less文件*/
    gulp.task('watch',function(){
        return gulp.watch('less/**/*.less',['less']);
    });

    /*压缩css文件*/
    gulp.task('mincss',function(){
        gulp.src(['css/**/*.css','!css/common.css','!css/head.css','!css/footer.css'])
            .pipe(cssver())
            .pipe(mincss({compatibility:'ie7'}))
            .pipe(gulp.dest('../dist/css/'));
    });

    /*压缩js文件*/
    gulp.task('minjs',function(){
        gulp.src(['js/**/*.js','!js/libs/**/*.js'])
            .pipe(uglify({mangle:false}))
            .pipe(gulp.dest('../dist/js/'));
        gulp.src(['js/libs/**/*.js'])
            .pipe(gulp.dest('../dist/js/libs/'));
        gulp.src(['data/*.json'])
            .pipe(gulp.dest('../dist/data/'));
    });

    /*压缩图片*/
    gulp.task('minimg',function(){
        gulp.src('img/**/*.{png,gif,jpeg}')
            // .pipe(cache(imgmin()))
            .pipe(gulp.dest('../dist/img/'));
    });

    /*html引用资源添加版本号*/
    gulp.task('rev',function(){
        gulp.src('html/**/*.html')
            .pipe(rev())
            .pipe(gulp.dest('../dist/views/'));
    });

    /* 
        合并请求, 
        如果不希望某一个js合并，需要添加data-ignore="true" 
        如：<script data-ignore="true" src="a.js"></script>
    */ 
    gulp.task('combo',function(){
        var baseUri = 'http://127.0.0.1:5678/combo?f=';
        var src = {
            splitter: ','
        };
        gulp.src('html/**/*.html')
            .pipe(rev())
            .pipe(combo(baseUri,src))
            .pipe(gulp.dest('../dist/views/'));
    });

    gulp.task('default',['mincss','minimg','minjs','combo']);